<template>
  <div>
    <div class="search">
      <input
        class="search-input"
        type="text"
        placeholder="输入城市名或拼音"
        name="text"
        id="search"
        v-model="keyword"
      >
    </div>
    <div
      class="search-content"
      ref="content"
      v-show="keyword"
    >
      <ul>
        <li
          class="search-item border-bottom"
          v-for="item of list"
          :key="item.id"
          @click="handleCityClick(item.name)"
        >{{item.name}}</li>
        <li
          class="search-item border-bottom"
          v-show="hasNoData"
        >
          没有找到搜索结果
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'

export default {
  name: 'CitySearch',
  data () {
    return {
      keyword: '',
      list: [],
      timer: 0,
      hasNoData: false
    }
  },
  props: {
    cities: Object
  },
  methods: {
    handleCityClick (city) {
      this.$store.commit('changeCity', city)
      this.$router.push('/')
      this.keyword = ''
    }
  },
  watch: {
    keyword () {
      if (!this.keyword) {
        this.list = []
        // return
      } else {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          const result = []
          for (let i in this.cities) {
            this.cities[i].forEach(item => {
              // 判断每一个城市对象的中文和中文拼音中是否带有 keyword 的值，有则就将此项添加到 result 中
              if (item.spell.indexOf(this.keyword) > -1 || item.name.indexOf(this.keyword) > -1) {
                result.push(item)
              }
            })
          }
          this.list = result
          // 当循环完之后，根据数组中是否有值返回相应的状态
          this.hasNoData = !result.length
        }, 50)
      }
    }
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.content)
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/variables.styl'

.search
  height 0.72rem
  padding 0.1rem
  background $bgColor

  .search-input
    box-sizing border-box
    width 100%
    height 0.72rem
    padding 0.1rem
    line-height 0.62rem
    text-align center
    border-radius 0.06rem
    color #666

.search-content
  z-index 1
  overflow hidden
  position absolute
  top 1.78rem
  bottom 0
  left 0
  right 0
  background-color #fff

  .search-item
    line-height 0.62rem
    padding-left 0.2rem
    background-color #fff
    color #666
</style>
